package com.yonyou.pmclouds.basecom.dao.typehandler;

import org.apache.ibatis.type.DateTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;
import java.util.GregorianCalendar;

/**
 * Date的转换方法，保证Date持久化时不会出现null,待处理日期、处理时间
 * <p>
 * 将1000-1-1 0：0：0 定义为null，一般不会命中这个时间
 *
 * @author mapeif
 */
@MappedJdbcTypes(value = {JdbcType.TIMESTAMP, JdbcType.DATE}, includeNullJdbcType = true)
public class NonNullDateTypeHandler extends DateTypeHandler {
    public final static Date DEFUALT_DATE =
            new GregorianCalendar(1000, 0, 1, 0, 0, 0).getTime();

    @Override
    public Date getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return getNullDate(super.getNullableResult(rs, columnName));
    }

    @Override
    public Date getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return getNullDate(super.getNullableResult(rs, columnIndex));
    }

    @Override
    public Date getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return getNullDate(super.getNullableResult(cs, columnIndex));
    }

    @Override
    public void setParameter(PreparedStatement ps, int i, Date parameter, JdbcType jdbcType) throws SQLException {
        setNonNullParameter(ps, i, parameter == null ? DEFUALT_DATE : parameter, jdbcType);
    }

    protected Date getNullDate(Date date) {
        if (DEFUALT_DATE.equals(date)) {
            return null;
        }
        return date;
    }
}
